package com.egoonet.web;

import com.egoonet.dao.PostRepository;
import com.egoonet.domain.Post;
import com.egoonet.domain.PostUser;
import com.egoonet.domain.QPost;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by wchi on 2017/4/29.
 */
@RestController
@Slf4j
public class QuerydslController {
    @Autowired
    PostRepository postRepository;

    @Autowired
    @PersistenceContext
    private EntityManager entityManager;

    private JPAQueryFactory queryFactory;

    @PostConstruct
    public void init(){
        queryFactory = new JPAQueryFactory(entityManager);
    }

    /**
     * Querydsl测试
     * @return
     */
    @RequestMapping(value="/querydsl/test1", method = RequestMethod.GET)
    public Post test1(){
        QPost qPost = QPost.post;
        Predicate predicate = qPost.isdn.eq(5);
        Post p = postRepository.findOne(predicate);
        return p;
    }

    @RequestMapping(value="/querydsl/test2", method = RequestMethod.GET)
    public List<Post> test2(){
        QPost qPost = QPost.post;
        List<Post> postList = queryFactory.selectFrom(qPost)
                .where(
                        qPost.isdn.eq(5),
                        qPost.id.eq(5L)
                        )
                .fetch();
        return postList;
    }


}
